﻿// content-script.js
console.log(".pakchoi-1.0");

const SAVE_KEY = "c9(*G234S*DhfgWfds";
const DEFAULT_CONF = {
	waiting_time: 2000,
	send_messages: [],
};
const source_data = JSON.parse(localStorage.getItem(SAVE_KEY) || JSON.stringify(DEFAULT_CONF));
const data = new Proxy(source_data, {
	set(source, prop, value) {
		source[prop] = value;
		localStorage.setItem(SAVE_KEY, JSON.stringify(source));
		return source;
	},
});

function fireKeyEvent(element, evtType, keyChar) {
	element.focus();
	var KeyboardEventInit = { key: keyChar, code: "", location: 0, repeat: false, isComposing: false };
	var evtObj = new KeyboardEvent(evtType, KeyboardEventInit);
	element.dispatchEvent(evtObj);
}

function injectjs(str) {
	const jsdom = document.createElement("script");
	jsdom.innerText = str;
	document.querySelector("body").appendChild(jsdom);
}

const timesleep = (time) =>
	new Promise((ok) =>
		setTimeout(() => {
			ok();
		}, time)
	);

let index = 1;
let page = 1;

(async function toudi() {
	const { waiting_time, open_the_tools, send_messages } = data;
	if (!open_the_tools) {
		await timesleep(3000);
		console.warn("未开启");
		return toudi();
	}
	await timesleep(waiting_time);
	console.log(`start:page-${page} // index-${index} (wait=${waiting_time})`);
	if (index == 15) {
		// 翻页
		document.querySelector(".ui-icon-arrow-right").click();
		index = 1;
		await timesleep(waiting_time);
	}
	document.querySelector(`li:nth-child(${index}) > div.job-card-body.clearfix > a > div.job-info.clearfix > a`).click();
	await timesleep(waiting_time);
	if (send_messages && send_messages.length) {
		const btn = document.querySelector(".btn-send");
		const ipt = document.querySelector(".chat-input");
		btn.classList.remove("disabled");
		for (let message of send_messages) {
			ipt.innerText = message;
			injectjs(`window.Vue.app.$children[0].$children[3].$children[1].$children[3].enableSubmit = true;`);
			btn.click();
			await timesleep(waiting_time);
		}
	}
	window.history.back();
	index += 1;
	toudi();
})();

// // 监听popup的message
chrome.runtime.onConnect.addListener((res) => {
	if (res.name === "bosstools") {
		res.onMessage.addListener(({ command, reqdata }) => {
			let resdata = "ok[default]";
			switch (command) {
				case "setdata":
					Object.assign(data, reqdata);
				case "getdata":
					resdata = JSON.parse(JSON.stringify(data));
			}
			res.postMessage(resdata);
		});
	}
});
